package com.taokatao.cardmee.business.cardcrud;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.taokatao.cardmee.ActivityCollector;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.UploadCardIconInfo;
import com.taokatao.cardmee.api.model.UploadCardPictureInfo;
import com.taokatao.cardmee.business.MainActivity;
import com.taokatao.cardmee.common.widget.AlertDialog;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.db.model.Card;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CardInfoEditActivity extends BaseActivity implements View.OnClickListener, TitleLayout.Callback {
    @BindView(R.id.l_title) TitleLayout lTitle;

    @BindView(R.id.i_custom) ImageView iCustom;
    @BindView(R.id.i_icon) ImageView iIcon;
    @BindView(R.id.l_top) View lTop;
    @BindView(R.id.t_delete) TextView tDelete;
    @BindView(R.id.t_more) TextView tMore;
    @BindView(R.id.t_code) TextView tCode;
    @BindView(R.id.i_pic_front) ImageView iPicFront;
    @BindView(R.id.i_pic_back) ImageView iPicBack;
    @BindView(R.id.i_scan_code) ImageView iScanCode;
    @BindView(R.id.t_tel) TextView tTel;
    @BindView(R.id.t_username) TextView tUsername;
    @BindView(R.id.l_code) View lCode;
    @BindView(R.id.l_username) View lUsername;
    @BindView(R.id.l_tel) View lTel;
    @BindView(R.id.l_more) View lMore;

    @BindString(R.string.digits_no_chinese_char) String digitsNoChineseChar;

    private boolean isCustomMode;
    private Card c;
    private String pictureSelect = "picture_front";

    private String sLocalPicFront, sLocalPicBack, sLocalBusinessIcon;
    private String sUploadedFrontUrl, sUploadedBackUrl, sUploadedIconUrl;

    private SheetDialog dlgSheet;
    private AlertDialog dlgDelete;
    private int styleColor;

    static final int REQUEST_CODE_CARD_EDIT_CODE = 1043;
    static final int REQUEST_CODE_CARD_EDIT_USERNAME = 1044;
    static final int REQUEST_CODE_CARD_EDIT_TEL = 1045;
    static final int REQUEST_CODE_CARD_EDIT_MORE = 1046;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_info_edit);
        ButterKnife.bind(this);

        c = App.i().getGson().fromJson(getIntent().getStringExtra("extra_card"), Card.class);
        isCustomMode = C.settings.BUSINESS_OTHER_ID == c.getBusinessId();
        lTitle.setCallback(this);
        Utils.throttleFirstClick(iScanCode, this);

        if (isCustomMode) {
            styleColor = 0xFF4C4C4C;
            iCustom.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(c.getBuPic())) {
                Glide.with(this).load(c.getBuPic()).centerCrop().bitmapTransform(App.i().getCropCircleTransformation()).into(iIcon);
            }
        } else {
            if (!TextUtils.isEmpty(c.getBackColor()) && c.getBackColor().length() == 7 && c.getBackColor().startsWith("#")) {
                styleColor = Color.parseColor(c.getBackColor());
            } else {
                styleColor = 0xFF4C4C4C;
            }
            if (!TextUtils.isEmpty(c.getMCardIcon())) {
                Glide.with(this).load(c.getMCardIcon()).centerCrop().into(iIcon);
            }
        }

        lTop.setBackgroundColor(styleColor);
        lTitle.setBackgroundColor(styleColor);

        if (!TextUtils.isEmpty(c.getPositiveIcon())) {
            Glide.with(this).load(c.getPositiveIcon()).into(iPicFront);
        }
        if (!TextUtils.isEmpty(c.getBackIcon())) {
            Glide.with(this).load(c.getBackIcon()).into(iPicBack);
        }
        tCode.setText(c.getMCardNo());
        tMore.setText(c.getRemark());
        tUsername.setText(c.getCardUser());
        tTel.setText(c.getCardTel());
    }

    @Override
    public void onMenuClick(TitleLayout lTitle, String flag) {
        Utils.onMobEvent(CardInfoEditActivity.this, "clickSaveButtonOfCardEdit");
        String mCardNo = tCode.getText().toString().replaceAll(" ", "");
        String mCardUser = tUsername.getText().toString().trim();
        String mCardTel = tTel.getText().toString().trim();
        if (TextUtils.isEmpty(mCardNo) && (TextUtils.isEmpty(mCardUser) || TextUtils.isEmpty(mCardTel))) {
            Utils.showToast("信息不全");
            return;
        }

        if (!TextUtils.isEmpty(sLocalBusinessIcon)) {
            requestUploadCardIcon();
        } else if (!TextUtils.isEmpty(sLocalPicFront) || !TextUtils.isEmpty(sLocalPicBack)) {
            requestUploadCardPicture();
        } else {
            requestUpdateCard();
        }
    }

    @Override
    @OnClick({R.id.i_pic_front, R.id.i_pic_back, R.id.t_delete, R.id.l_code, R.id.l_username, R.id.l_tel, R.id.l_more, R.id.i_custom})
    public void onClick(View v) {
        if (v == iScanCode) {
            Utils.onMobEvent(this, "clickScanOfAddCard");
            Intent intent = new Intent(this, CardCodeScanActivity.class);
            intent.putExtra("extra_name", isCustomMode ? c.getAnotherBusiness() : c.getBusinessName());
            intent.putExtra("launcher_mode", "input");
            startActivityForResult(intent, REQUEST_CODE_SCAN_CODE);
        } else if (v == iCustom) {
            pictureSelect = "picture_icon";
            cropAspectX = 1;
            cropAspectY = 1;
            expectedOutputCropWidth = 300;
            expectedOutputCropHeight = (int) (1f * expectedOutputCropWidth * cropAspectY / cropAspectX);

            new SheetDialog.Builder(this)
                    .addMenu("拍照", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            lastCameraRequestAction = "sysShoot";
                            openCamera();
                        }
                    }).addMenu("从相册选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openPhotos();
                        }
                    }).create().show();
        } else if (v == iPicFront) {
            pictureSelect = "picture_front";
            cropAspectX = 1000;
            cropAspectY = 618;
            expectedOutputCropWidth = 500;
            expectedOutputCropHeight = (int) (1f * expectedOutputCropWidth * cropAspectY / cropAspectX);
            showCardPictureDialog();
        } else if (v == iPicBack) {
            pictureSelect = "picture_back";
            cropAspectX = 1000;
            cropAspectY = 618;
            expectedOutputCropWidth = 500;
            expectedOutputCropHeight = (int) (1f * expectedOutputCropWidth * cropAspectY / cropAspectX);
            showCardPictureDialog();
        } else if (v == tDelete) {
            showDeleteDialog();
        } else if (v == lCode) {
            Intent intent = new Intent(this, InfoEditActivity.class);
            intent.putExtra("extra_content", tCode.getText().toString().replaceAll(" ", ""));
            intent.putExtra("extra_input_type", InputType.TYPE_CLASS_NUMBER);
            intent.putExtra("extra_digits", digitsNoChineseChar);
            intent.putExtra("extra_max_length", 300);
            startActivityForResult(intent, REQUEST_CODE_CARD_EDIT_CODE);
        } else if (v == lUsername) {
            Intent intent = new Intent(this, InfoEditActivity.class);

            String value = tUsername.getText().toString();
            if (TextUtils.isEmpty(value)) {
                value = App.i().getCurrUser().getRealName();
                intent.putExtra("extra_need_changed", false);
            }
            intent.putExtra("extra_content", value);
            intent.putExtra("extra_max_length", 20);
            startActivityForResult(intent, REQUEST_CODE_CARD_EDIT_USERNAME);
        } else if (v == lTel) {
            Intent intent = new Intent(this, InfoEditActivity.class);
            String value = tTel.getText().toString();
            if (TextUtils.isEmpty(value)) {
                value = App.i().getCurrUser().getUserTel();
                intent.putExtra("extra_need_changed", false);
            }
            intent.putExtra("extra_content", value);
            intent.putExtra("extra_input_type", InputType.TYPE_CLASS_NUMBER);
            intent.putExtra("extra_max_length", 20);
            startActivityForResult(intent, REQUEST_CODE_CARD_EDIT_TEL);
        } else if (v == lMore) {
            Intent intent = new Intent(this, InfoEditActivity.class);
            intent.putExtra("extra_content", tMore.getText().toString());
            intent.putExtra("extra_max_length", 200);
            startActivityForResult(intent, REQUEST_CODE_CARD_EDIT_MORE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CARD_EDIT_CODE) {
            if (resultCode == RESULT_OK) {
                tCode.setText(Utils.formatCardCode(data.getStringExtra("result")));
            }
        } else if (requestCode == REQUEST_CODE_CARD_EDIT_USERNAME) {
            if (resultCode == RESULT_OK) {
                tUsername.setText(data.getStringExtra("result"));
            }
        } else if (requestCode == REQUEST_CODE_CARD_EDIT_TEL) {
            if (resultCode == RESULT_OK) {
                tTel.setText(data.getStringExtra("result"));
            }
        } else if (requestCode == REQUEST_CODE_CARD_EDIT_MORE) {
            if (resultCode == RESULT_OK) {
                tMore.setText(data.getStringExtra("result"));
            }
        } else if (requestCode == REQUEST_CODE_SCAN_CODE) {
            if (resultCode == RESULT_OK) {
                String content = data.getStringExtra("extra_content");
                String format = data.getStringExtra("extra_format");
                Utils.logd(getClass().getSimpleName() + " scan content [type:" + format + "] is : " + content);
                Utils.onMobEvent(this, "scanBarcode");
                tCode.setText(content);
            }
        }
    }

    String lastCameraRequestAction = "";

    @Override
    protected void onCameraPermissionAllowed() {
        if (TextUtils.equals("customShoot", lastCameraRequestAction)) {
            Intent intent = new Intent(CardInfoEditActivity.this, CardEasyCameraActivity.class);
            startActivity(intent);
        }
    }

    private void showCardPictureDialog() {
        if (dlgSheet == null) {
            dlgSheet = new SheetDialog.Builder(this)
                    .addMenu("拍照", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            if (!AndPermission.hasPermission(CardInfoEditActivity.this, Manifest.permission.CAMERA)) {
                                lastCameraRequestAction = "customShoot";
                                AndPermission.with(CardInfoEditActivity.this)
                                        .requestCode(CODE_FOR_CAMERA_PERMISSION)
                                        .permission(Manifest.permission.CAMERA)
                                        .send();
                                return;
                            }

                            Intent intent = new Intent(CardInfoEditActivity.this, CardEasyCameraActivity.class);
                            startActivity(intent);
                        }
                    }).addMenu("从相册选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            openPhotos();
                        }
                    }).create();
        }
        dlgSheet.show();
    }

    private void showDeleteDialog() {
        if (dlgDelete == null) {
            dlgDelete = new AlertDialog.Builder(this).setTitle("提示").setMessage("确定要删除这张会员卡？")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            requestDeleteCard();
                            dialog.dismiss();
                        }
                    }).create();
        }
        dlgDelete.show();
    }

    private void requestDeleteCard() {
        ApiManager.i().deleteCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(),c.getIsMyCard(), new SubscriberAdapter<RespWrapper<RespInfo>>() {
            @Override
            public void onNext(RespWrapper<RespInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    Utils.postMainThreadBusEvent(BusEvent.CARD_DELETE, c);
                    ActivityCollector.finishAllExcept(MainActivity.class);
                }
            }
        }.showProgress(this));
    }

    @Override
    protected void onPictureQueryOut(String path) {
        super.onPictureQueryOut(path);
        if (TextUtils.equals(pictureSelect, "picture_front")) {
            Utils.onMobEvent(CardInfoEditActivity.this, "shotPositive");
            Glide.with(this).load(new File(sLocalPicFront = path)).into(iPicFront);
        } else if (TextUtils.equals(pictureSelect, "picture_back")) {
            Utils.onMobEvent(CardInfoEditActivity.this, "shotNegative");
            Glide.with(this).load(new File(sLocalPicBack = path)).into(iPicBack);
        } else if (TextUtils.equals(pictureSelect, "picture_icon")) {
            Glide.with(this).load(new File(sLocalBusinessIcon = path))
                    .bitmapTransform(App.i().getCropCircleTransformation()).into(iIcon);
        }
    }

    private void requestUploadCardIcon() {
        ApiManager.i().uploadCardIcon(this, new File(sLocalBusinessIcon), new SubscriberAdapter<RespWrapper<UploadCardIconInfo>>() {
            @Override
            public void onNext(RespWrapper<UploadCardIconInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    UploadCardIconInfo uploadCardIconInfo = o.decode(UploadCardIconInfo.class);
                    sUploadedIconUrl = uploadCardIconInfo.busIconUrl;

                    if (!TextUtils.isEmpty(sLocalPicFront) || !TextUtils.isEmpty(sLocalPicBack)) {
                        requestUploadCardPicture();
                    } else {
                        requestUpdateCard();
                    }
                }
            }
        }.showProgress(this));
    }

    private void requestUploadCardPicture() {
        File iPicFront = !TextUtils.isEmpty(sLocalPicFront) ? new File(sLocalPicFront) : null;
        File iPicBack = !TextUtils.isEmpty(sLocalPicBack) ? new File(sLocalPicBack) : null;

        Utils.loge("uploadCardPicture  iPicFront:" + (iPicFront != null ? iPicFront.getAbsolutePath() : "null"));
        Utils.loge("uploadCardPicture  iPicBack:" + (iPicBack != null ? iPicBack.getAbsolutePath() : "null"));

        ApiManager.i().uploadCardPicture(this, iPicFront, iPicBack, new SubscriberAdapter<RespWrapper<UploadCardPictureInfo>>() {
            @Override
            public void onNext(RespWrapper<UploadCardPictureInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    UploadCardPictureInfo uploadCardPictureInfo = o.decode(UploadCardPictureInfo.class);
                    sUploadedFrontUrl = uploadCardPictureInfo.positiveIconUrl;
                    sUploadedBackUrl = uploadCardPictureInfo.backIconUrl;

                    requestUpdateCard();
                }
            }
        }.showProgress(this));
    }

    private void requestUpdateCard() {
        final String remark = tMore.getText().toString().trim();
        final String mCardCode = tCode.getText().toString().replaceAll(" ", "");
        final String mUsername = tUsername.getText().toString().trim();
        final String mTel = tTel.getText().toString().trim();

        final boolean isChangedRemark = !TextUtils.equals(remark, c.getRemark());
        final boolean isChangediPicFront = !TextUtils.isEmpty(sUploadedFrontUrl);
        final boolean isChangediPicBack = !TextUtils.isEmpty(sUploadedBackUrl);
        final boolean isChangedIcon = !TextUtils.isEmpty(sUploadedIconUrl);
        final boolean isChangedCardCode = !TextUtils.equals(mCardCode, c.getMCardNo());
        final boolean isChangedUsername = !TextUtils.equals(mUsername, c.getCardUser());
        final boolean isChangedTel = !TextUtils.equals(mTel, c.getCardTel());

        if (!isChangedRemark && !isChangediPicFront && !isChangediPicBack
                && !isChangedIcon && !isChangedCardCode && !isChangedUsername && !isChangedTel) {
            finish();
            return;
        }
        ApiManager.i().updateCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(),
                c.getMCardAliasName(), null, sUploadedFrontUrl, sUploadedBackUrl, remark,
                mCardCode, c.getAnotherBusiness(), sUploadedIconUrl, mUsername, mTel, new SubscriberAdapter<RespWrapper<RespInfo>>() {
                    @Override
                    public void onNext(RespWrapper<RespInfo> o) {
                        super.onNext(o);
                        if (o.code == C.http.RESULT_CODE_SUCCESS) {
                            if (isChangedRemark) c.setRemark(remark);
                            if (isChangediPicFront) c.setPositiveIcon(sUploadedFrontUrl);
                            if (isChangediPicBack) c.setBackIcon(sUploadedBackUrl);
                            if (isChangedIcon) c.setBuPic(sUploadedIconUrl);
                            if (isChangedCardCode) c.setMCardNo(mCardCode);
                            if (isChangedUsername) c.setCardUser(mUsername);
                            if (isChangedTel) c.setCardTel(mTel);

                            Utils.postMainThreadBusEvent(BusEvent.CARD_UPDATED, c);
                            ActivityCollector.finishAllExcept(MainActivity.class);
                        }
                    }
                }.showProgress(this));
    }

    @Override
    public void onEventMainThread(BusEvent event) {
        super.onEventMainThread(event);
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.CARD_CAMERA_SAVED:
                    File savedByEaseCamera = (File) event.content;
                    cropImage(Uri.fromFile(savedByEaseCamera));
                    break;
            }
        }
    }
}
